package bg.btanev.eightyfour.shared.state;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author B.Tanev
 *
 */
public enum TargetState {
	INITIALIZED('I'), TOPROCESS('T'), PROCESSING('P'), UPDATED('U'), DEACTIVE('D'), ACTIVE('A');

	private static final char STATE_INITIALIZED = 'I';
	private static final char STATE_TOPROCESS = 'T';
	private static final char STATE_PROCESSING = 'P';
	private static final char STATE_UPDATED = 'U';
	private static final char STATE_DEACTIVE = 'D';
	private static final char STATE_ACTIVE = 'A';

	private final char state;
	private final Set<Character> permitedValues;

	private TargetState(char state) {
		this.state = state;
		this.permitedValues = initTransitionPermissions();
	}

	private Set<Character> initTransitionPermissions() {
		Set<Character> transitionPermissions = new HashSet<Character>(6);

		switch (this.state) {
			case STATE_INITIALIZED:
				transitionPermissions.addAll(Arrays.asList(new Character[] { null }));
				break;

			case STATE_TOPROCESS:
				transitionPermissions.addAll(Arrays.asList(new Character[] { STATE_INITIALIZED, STATE_UPDATED }));
				break;

			case STATE_PROCESSING:
				transitionPermissions.addAll(Arrays.asList(new Character[] { STATE_TOPROCESS }));
				break;

			case STATE_UPDATED:
				transitionPermissions.addAll(Arrays.asList(new Character[] { STATE_PROCESSING }));
				break;

			case STATE_DEACTIVE:
				transitionPermissions.addAll(Arrays.asList(new Character[] { null, STATE_ACTIVE }));
				break;

			case STATE_ACTIVE:
				transitionPermissions.addAll(Arrays.asList(new Character[] { null, STATE_DEACTIVE }));
				break;

			default:
				throw new Error("Invalid target state! " + this.state);
		}

		return transitionPermissions;
	}

	public boolean isTransitionValid(TargetState fromState) {
		boolean transitionValid = this.permitedValues.contains(fromState != null ? fromState.state : null);
		return transitionValid;
	}
}
